﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using NDK.Module.Model;
using NDK.Module.BLL;


namespace NDK.Motion.BLL
{
    public class PostMsg
    {
        /// <summary>
        /// 卡站
        /// </summary>
        /// <param name="url"></param>
        /// <param name="Producttype"></param>
        /// <param name="CurrentSetp"></param>
        /// <param name="Barcode"></param>
        /// <returns></returns>
        public static string OPIDCheck(string Barcode)
        {
            TrackerInData track = new TrackerInData();
            track.Barcode = Barcode;            //条码
            track.CurrentSetp = Common.当前工站;    //当前站
            track.Product = Common.产品型号;    //产品类型
            track.Method = "GetBarcodeStatus";  //固定值

            string strMsg = JsonConvert.SerializeObject(track);
            System.Diagnostics.Debug.WriteLine(strMsg);
            string msg = Post(strMsg, Common.服务器地址);
            return msg;
        }

        /// <summary>
        /// 出站接口
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string TrackOut(MeasureProduct measureProduct)
        {
            Track track = new Track();
            track.product = Common.产品型号;         
            track.stationNo = Common.工位信息;         
            track.machineName = Common.设备电脑名;    

            List<testList> testList = new List<testList>();
            foreach (var item in measureProduct.MeasureData)
            {
                testList.Add(new PostMsg.testList()
                {
                    fItem = item.Name,
                    fTime = measureProduct.EndTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    fMin = measureProduct.measureSizeList.SingleOrDefault(name => name.SizeName == item.Name).LowerDeviation.ToString(),
                    fMax = measureProduct.measureSizeList.SingleOrDefault(name => name.SizeName == item.Name).UpperDeviation.ToString(),
                    fValue = item.Value.ToString(),
                    fResult = item.JugeResult == JUDGEMENT_RESULT.OK.ToString() ? "1" : "0"
                });
            }

            track.barCodeList = new List<barCodeList>
            {
                new barCodeList()
                {
                    barCode = measureProduct.SN,
                    fDate = measureProduct.EndTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    result = measureProduct.OK_NG == "OK" ? "1" : "0",
                    testList = testList
                }
            };

            string strMsg = JsonConvert.SerializeObject(track);
            System.Diagnostics.Debug.WriteLine(strMsg);
            string msg = Post(strMsg, Common.服务器地址);
            return msg;
        }


        #region 发送post请求
        private static string Post(string str, string url)
        {
            PublicMethod.writeLog("发：" + str, "MesLog", true);
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Proxy = null;
            req.Method = "POST";
            //req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            req.ContentType = "application/json";

            //str = HttpUtility.UrlEncode(str);      //Url转码
            //str = WebUtility.UrlEncode(str);      //Url转码
            //byte[] data = Encoding.UTF8.GetBytes("message=" + str);//把字符串转换为字节
            byte[] data = Encoding.UTF8.GetBytes(str);//把字符串转换为字节
            req.ContentLength = data.Length; //请求长度
            try
            {
                using (Stream reqStream = req.GetRequestStream()) //获取
                {
                    reqStream.Write(data, 0, data.Length);//向当前流中写入字节
                    reqStream.Close(); //关闭当前流
                }
            }
            catch (Exception ex)
            {
                result = "上传失败！" + ex.Message;

            }
            //获取响应内容
            try
            {
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); //响应结果
                Stream stream = resp.GetResponseStream();
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {

                    result = reader.ReadToEnd();
                }
            }
            catch
            {
                result = "数据上传网络无权限访问，请联系咨询检查服务端网络是否异常！";
                MessageBox.Show("数据上传网络无权限访问，请联系咨询检查服务端网络是否异常！");
            }
            PublicMethod.writeLog("收：  " + result, "MesLog", true);
            return result;
        }

        #endregion

        private class TrackerInData
        {
            public string Barcode { get; set; }
            public string CurrentSetp { get; set; }
            public string Method { get; set; }
            public string Product { get; set; }
        }

        private class Track
        {
            public string product { get; set; }
            public string stationNo { get; set; }
            public string machineName { get; set; }
            public List<barCodeList> barCodeList { get; set; }

        }

        public class barCodeList
        {
            public string barCode { get; set; }
            public string fDate { get; set; }
            public string result { get; set; }
            public string errorCode { get; set; }
            public string remark { get; set; }
            public List<testList> testList { get; set; }
        }

        public class testList
        {
            public string fItem { get; set; }
            public string fTime { get; set; }
            public string fMin { get; set; }
            public string fMax { get; set; }
            public string fValue { get; set; }
            public string fUnit { get; set; }
            public string fResult { get; set; }
            public string fDescription { get; set; }
        }
    }
}
